package org.example.lethear.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.lethear.dto.category.CategoryCreateRequest;
import org.example.lethear.dto.category.CategoryDTO;
import org.example.lethear.entity.Category;
import org.example.lethear.repository.CategoryRepository;
import org.example.lethear.utils.Result;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 分类管理控制器
 */
@Tag(name = "分类管理", description = "分类的增删改查相关接口")
@RestController
@RequestMapping("/categories")
@RequiredArgsConstructor
public class CategoryController {
    
    private final CategoryRepository categoryRepository;
    
    /**
     * 获取所有分类
     */
    @Operation(summary = "获取分类列表", description = "获取所有可用的分类")
    @GetMapping
    public Result<List<CategoryDTO>> getCategories() {
        List<Category> categories = categoryRepository.findEnabledCategoriesOrderBySortOrder();
        List<CategoryDTO> categoryDTOs = categories.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        return Result.success("获取成功", categoryDTOs);
    }
    
    /**
     * 获取分类详情
     */
    @Operation(summary = "获取分类详情", description = "根据ID获取分类详情")
    @GetMapping("/{categoryId}")
    public Result<CategoryDTO> getCategoryById(@Parameter(description = "分类ID") @PathVariable Long categoryId) {
        Category category = categoryRepository.findById(categoryId)
                .orElseThrow(() -> new RuntimeException("分类不存在"));
        CategoryDTO categoryDTO = convertToDTO(category);
        return Result.success("获取成功", categoryDTO);
    }
    
    /**
     * 创建分类
     */
    @Operation(summary = "创建分类", description = "创建新的分类")
    @PostMapping
    public Result<CategoryDTO> createCategory(@Valid @RequestBody CategoryCreateRequest request) {
        Category category = new Category();
        category.setName(request.getName());
        category.setDescription(request.getDescription());
        category.setParentId(request.getParentId() != null ? request.getParentId() : 0L);
        category.setSortOrder(request.getSort() != null ? request.getSort() : 0);
        category.setStatus(request.getStatus());
        
        category = categoryRepository.save(category);
        CategoryDTO categoryDTO = convertToDTO(category);
        return Result.success("创建成功", categoryDTO);
    }
    
    /**
     * 更新分类
     */
    @Operation(summary = "更新分类", description = "更新现有分类")
    @PutMapping("/{categoryId}")
    public Result<CategoryDTO> updateCategory(
            @Parameter(description = "分类ID") @PathVariable Long categoryId,
            @Valid @RequestBody CategoryCreateRequest request) {
        Category category = categoryRepository.findById(categoryId)
                .orElseThrow(() -> new RuntimeException("分类不存在"));
        
        category.setName(request.getName());
        category.setDescription(request.getDescription());
        if (request.getParentId() != null) {
            category.setParentId(request.getParentId());
        }
        if (request.getSort() != null) {
            category.setSortOrder(request.getSort());
        }
        category.setStatus(request.getStatus());
        
        category = categoryRepository.save(category);
        CategoryDTO categoryDTO = convertToDTO(category);
        return Result.success("更新成功", categoryDTO);
    }
    
    /**
     * 删除分类
     */
    @Operation(summary = "删除分类", description = "删除指定分类")
    @DeleteMapping("/{categoryId}")
    public Result<Void> deleteCategory(@Parameter(description = "分类ID") @PathVariable Long categoryId) {
        Category category = categoryRepository.findById(categoryId)
                .orElseThrow(() -> new RuntimeException("分类不存在"));
        
        // 软删除：设置为不可用状态
        category.setStatus(0);
        categoryRepository.save(category);
        
        return Result.success("删除成功");
    }
    
    /**
     * 转换实体为DTO
     */
    private CategoryDTO convertToDTO(Category category) {
        CategoryDTO dto = new CategoryDTO();
        dto.setId(category.getId());
        dto.setName(category.getName());
        dto.setDescription(category.getDescription());
        dto.setParentId(category.getParentId());
        dto.setSort(category.getSortOrder());
        dto.setStatus(category.getStatus());
        dto.setCreateTime(category.getCreateTime());
        dto.setUpdateTime(category.getCreateTime()); // Category实体没有updateTime字段
        
        // 统计帖子数量（这里暂时设为0，后续可以添加实际统计逻辑）
        dto.setPostCount(0);
        
        return dto;
    }
} 